package com.hunhjy.shiro.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hunhjy.shiro.dto.common.UsersDto;
import com.hunhjy.shiro.services.UserService;

@Controller
public class ManageAction {
	// 日志记录
	private static Logger log = LogManager.getLogger();
	@Resource
	private UserService userService;

	@RequestMapping(value = "/login")
	public String loginJump() {
		log.info("==登陆页面跳转==");
		return "/shiro/login";
	}

	@RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
	public String login(HttpServletRequest request, UsersDto usersDto) {
		// 获取前台页面传的用户名密码
		String loginName = usersDto.getUsercode();
		String loginPassword = usersDto.getPassword();
		log.info("username:" + loginName + ";password:" + loginPassword);

		HttpSession session = request.getSession(true);
		String errorMessage = "";

		Subject user = SecurityUtils.getSubject();

		// 将前台传的用户名密码存入UsernamePasswordToken
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPassword);
		token.setRememberMe(true);

		try {
			// 认证方法，会执行WxAuthorizingRealm中的doGetAuthenticationInfo方法
			user.login(token);

			String userID = (String) user.getPrincipal();
			log.info("User [" + userID + "] logged in successfully.");
			session.setAttribute("USERNAME", userID);
			return "redirect:/main.do";
		} catch (UnknownAccountException uae) {
			errorMessage = "用户认证失败：" + "username wasn't in the system.";
			log.info(errorMessage);
		} catch (IncorrectCredentialsException ice) {
			errorMessage = "用户认证失败：" + "password didn't match.";
			log.info(errorMessage);
		} catch (LockedAccountException lae) {
			errorMessage = "用户认证失败：" + "account for that username is locked - can't login.";
			log.info(errorMessage);
		} catch (AuthenticationException e) {
			errorMessage = "登录失败错误信息：" + e;
			log.error(errorMessage);
			e.printStackTrace();
			token.clear();
		}
		session.setAttribute("ErrorMessage", errorMessage);
		return "error";
	}

	@RequestMapping(value = "/main")
	public String mainPage(HttpServletRequest request, ModelMap model) {
		log.info("进入mainPage的Controller");
		HttpSession session = request.getSession(true);
		Subject user = SecurityUtils.getSubject();
		String userID = (String) user.getPrincipal();
		log.info("当前用户：" + userID);
		session.setAttribute("USERNAME", userID);
		List<UsersDto> users = userService.getUsers(null);
		log.info("users.size:" + users.size());
		for (int i = 0; i < users.size(); i++) {
			System.out.println(users.get(i).getId() + "-" + users.get(i).getUsername() + "-"
					+ users.get(i).getPassword() + "-" + users.get(i).getSex());
		}
		model.addAttribute("users", users);
		return "/shiro/main";
	}
}
